package com.qidian.buy.interceptor;

import com.qidian.buy.service.ICustomerService;
import com.qidian.buy.util.JSONTools;
import com.qidian.buy.util.pojo.QDResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 郭浩
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private ICustomerService customerService;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        QDResult result = QDResult.fal();
        // 从请求参数中获取token
        String token = request.getParameter("token");
        if(token!=null && !token.equals("")){
            // 通过service查询用户信息
            QDResult cutomerResult = customerService.getCustomerByToken(token);
            Object obj = cutomerResult.getData();
            if(obj!=null){
                // 将用户信息放request的作用域中
                request.setAttribute("loginCustomer",obj);
                return true;
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONTools.object2json(result));
        return false;
    }
}
